<template>
  <div class="page-wrap">
    <!-- <div style="color: rgb(27, 76, 184);margin-bottom: 15px">
      <div class="addressIcon"></div>
      <span>当前位置：</span>
      <span style="cursor: pointer" @click="returnCompany">裁判审核</span>
      <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
      <span style="color: #333">{{ this.$route.query.sceneName }}</span>
      <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
      <span style="color: #333">审核报告</span>
    </div> -->
    <!-- :style="{ height: contentHei === 'auto' ? contentHei : `${contentHei}px` }" -->
    <div class="page-content">
      <div class="img-header">
        <!-- <div style="font-weight: 700;font-size: 18px;width: 120px;flex:none;">审核报告</div> -->
        <div class="page-wrap-query">
          <Button type="primary" @click="downloadAllReports" :loading="downloading" ghost
            >打包下载当前页报告</Button
          >
          <Button
            type="primary"
            @click="downloadReportsNew"
            :loading="searchDownloading"
            ghost
            style="margin-left: 8px"
            >打包下载报告</Button
          >
          <Button
            type="primary"
            @click="downloadReportRecord"
            :loading="recordDownloading"
            ghost
            style="margin-left: 8px"
            >下载统计信息</Button
          >
          <Button
            type="primary"
            @click="downloadTarget"
            :loading="targetDownloading"
            ghost
            style="margin-left: 8px"
            >下载目标</Button
          >
          <AuditLog :sceneId="sceneId" :projectId="projectId" :companyList="companyList" :groupList="groupData" :ruleList="ruleList" style="margin-left: 8px"></AuditLog>
          <!-- :loading="targetDownloading" -->
          <!-- <Button type="primary" @click="exportRank(false)" ghost style="margin-left: 8px"
            >导出攻击方排行</Button
          >
          <Button type="primary" @click="exportRank(true)" ghost style="margin-left: 8px"
            >导出防守方排行</Button
          > -->
          <!-- <Select filterable
            v-model="taskId"
            placeholder="任务"
            @on-change="changeTask"
            style="width:140px; margin-left: 8px"
          >
            <Option :value="item.id" v-for="item in taskList" :key="item.id" :title="item.name">{{
              item.name
            }}</Option>
          </Select> -->
          <!-- daterange -->
          <DatePicker
            format="yyyy-MM-dd HH:mm"
            type="datetimerange"
            v-model="searchCheckTime"
            :editable="false"
            @on-change="changeTime($event, 1)"
            placement="bottom-end"
            placeholder="选择审核起止时间"
            clearable
            style="width: 280px;margin-left: 8px;"
            class="noConfirm"
          ></DatePicker>
          <DatePicker
            format="yyyy-MM-dd HH:mm"
            type="datetimerange"
            v-model="searchUploadTime"
            :editable="false"
            @on-change="changeTime($event, 2)"
            placement="bottom-end"
            placeholder="选择提交起止时间"
            clearable
            style="width: 280px;margin-left: 8px;"
            class="noConfirm"
          ></DatePicker>
          <Select filterable
            v-model="targetName"
            placeholder="目标"
            @on-change="selectStatus"
            multiple
            filterable
            :max-tag-count="2"
            style="width:280px; margin-left: 8px"
          >
            <Option :value="item.id" v-for="item in targetData" :key="item.id" :title="item.name">{{
              item.name
            }}</Option>
          </Select>
          <!-- <Input
            v-model.trim="targetName"
            placeholder="目标"
            style="width:120px; margin-left: 8px"
            @on-change="selectStatus"
          ></Input>-->
          <!-- <Input
            v-model.trim="groupName1"
            placeholder="团队名称"
            style="width:120px; margin-left: 8px"
            @on-change="selectStatus"
          ></Input> -->
          <Select filterable
            v-model="groupName1"
            placeholder="团队名称"
            @on-change="selectStatus"
            multiple
            filterable
            :max-tag-count="2"
            style="width:280px; margin-left: 8px"
          >
            <Option :value="item.id" v-for="item in groupData" :key="item.id" :title="item.name">{{
              item.name
            }}</Option>
          </Select>
          <Select filterable
            v-model="company"
            filterable
            placeholder="单位"
            clearable
            style="width:120px; margin-left: 8px"
            @on-change="selectStatus"
          >
            <Option :value="item" v-for="item in companyList" :key="item" :title="item">{{
              item
            }}</Option>
          </Select>
          <!-- <Select filterable
            v-model="type"
            filterable
            placeholder="报告类型"
            clearable
            style="width:120px; margin-left: 8px"
            @on-change="selectStatus"
          >
            <Option :value="1">攻击报告</Option>
            <Option :value="2">防御报告</Option>
          </Select> -->
          <!-- <Select filterable
            transfer
            v-model="publicTarget"
            placeholder="是否公共目标"
            filterable
            clearable
            style="width:120px; margin-left: 8px"
            @on-change="selectStatus"
          >
            <Option value="1">是</Option>
            <Option value="0">否</Option>
          </Select>-->
          <!-- <Select filterable
            v-model="attackType"
            filterable
            placeholder="攻击类型"
            clearable
            style="width:120px; margin-left: 8px"
            @on-change="selectStatus"
          >
            <Option :value="item.id" v-for="item in attackList" :key="item.id" :title="item.name">{{
              item.name
            }}</Option>
          </Select> -->
          <!-- <Cascader
            :render-format="renderFormat"
            transfer
            :data="extent4DefenseTypesData"
            v-model="defenseTypes"
            placeholder="防守类型"
            style="width:120px; margin-left: 8px"
            filterable
            clearable
            @on-change="selectStatus"
          ></Cascader>
          <Cascader
            :render-format="renderFormat"
            transfer
            :data="extent4InjuryData"
            v-model="attackLevel"
            placeholder="危害程度"
            style="width:120px; margin-left: 8px"
            filterable
            clearable
            @on-change="selectStatus"
          ></Cascader> -->
          <!-- <Select filterable v-model="level" placeholder="危险等级" clearable style="width:120px; margin-left: 8px" @on-change="selectStatus">
                        <Option value="high">高危</Option>
                        <Option value="middle">中危</Option>
                        <Option value="low">低危</Option>
                    </Select> -->
          <Select filterable
            v-model="statusModel"
            placeholder="审核状态"
            clearable
            multiple
            style="width:180px;margin-left: 8px"
            @on-change="selectStatus"
          >
            <Option value="1">未审核</Option>
            <Option value="2">已通过</Option>
            <Option value="3">已驳回</Option>
            <Option value="4">已挂起</Option>
            <Option value="5">驳回后再提交</Option>
          </Select>
          <Input
            v-model.trim="reportName1"
            placeholder="报告名称"
            clearable
            style="width:150px; margin-left: 8px"
            @on-change="selectStatus"
          ></Input>
          <Input
              v-if="[1,2,3].includes(hwTypeExtension)"
              v-model.trim="businessLoopholeOtherIds"
              placeholder="编号"
              clearable
              style="width:150px; margin-left: 8px"
              @on-change="selectStatus"
          ></Input>
          <Input
            v-if="[1,2,3].includes(hwTypeExtension)"
            v-model.trim="businessLoopholeName"
            placeholder="漏洞名称"
            clearable
            style="width:150px; margin-left: 8px"
            @on-change="selectStatus"
          ></Input>

          <Input
              v-if="[1,2,3].includes(hwTypeExtension)"
              v-model.trim="serchOther.url"
              placeholder="URL"
              clearable
              style="width:150px; margin-left: 8px"
              @on-change="selectStatus"
          ></Input>

          <Input
              v-if="[1,2,3].includes(hwTypeExtension)"
              v-model.trim="serchOther.creatorName"
              placeholder="提交人"
              clearable
              style="width:150px; margin-left: 8px"
              @on-change="selectStatus"
          ></Input>

<!--          <Input-->
<!--              v-if="[1,2,3].includes(hwTypeExtension)"-->
<!--              v-model.trim="serchOther.userId"-->
<!--              placeholder="最后审核人"-->
<!--              clearable-->
<!--              style="width:150px; margin-left: 8px"-->
<!--              @on-change="selectStatus"-->
<!--          ></Input>-->

          <Select filterable
              v-model="serchOther.userId"
              placeholder="审核人"
              filterable
              clearable
              style="width:180px;margin-left: 8px"
              @on-change="selectStatus"
          >
            <Option :value="user.userId" v-for="user in reflist" :key="user.userName">{{user.userName}}</Option>
          </Select>




          <Button
            class="header-btn"
            type="primary"
            ghost
            style="height: 32px;margin-left: 8px"
            @click="refreshSceneList"
          >
            <i class="el-icon-refresh-right" />
          </Button>
        </div>
      </div>
      <!-- <Divider /> -->
      <div class="content-wrap">
        <TableList
          :columns="reportCol"
          :data="reportList"
          :total="dataTotal"
          :size.sync="pageSize"
          :page.sync="reportPage"
          @queryFun="getReportList">
        </TableList>
        <!-- <card-list
          :columns="reportCol"
          :data="reportList"
          style="max-height: fit-content;"
        ></card-list> -->
      </div>
      <!-- <div
        style="display: flex;justify-content: center;margin: 15px 0"
        v-if="reportList.length > 0"
      >
        <Page
          :total="dataTotal"
          @on-change="changePageNum"
          show-total
          show-elevator
          :page-size="pageSize"
          :current="reportPage"
        />
      </div> -->
    </div>

    <!--报告文件-->
    <Modal
      v-model="fileModal"
      :title="`${this.currentType === 2 ? '防御报告' : '攻击报告'}文件列表`"
      width="800px"
      :mask-closable="false"
    >
      <Table border :columns="fileCol" :data="fileList"  :disable-expand='true'></Table>
      <div slot="footer">
        <Button @click="fileModal = false" v-if="extension.hwType!=2&&!extension.vpn">关闭</Button>
        <Button @click="downloadReports" type="primary" :loading="downloading1" v-if="extension.hwType!=2&&!extension.vpn">打包下载</Button>
        <!--  v-show="currentType !== 2" -->
      </div>
    </Modal>
    <!--审核报告-->
    <Modal
      v-model="reviewReportModal"
      :title="reviewReportTitle"
      width="800px"
      :footer-hide="true"
      @on-visible-change="changeModalStatus"
      :mask-closable="false"
    >
      <div>
        <div style="text-align: right;margin-bottom:10px;">
          <AuditLog :sceneId="sceneId" :projectId="projectId" :id="currentTarget.id" :ruleList="ruleList" style="margin-left: 8px;display: inline-block;"></AuditLog>
          <Button type="primary" @click="openTargetReportModal" v-if="currentTarget.type == 2"
            >被攻击记录</Button
          >
          <Button type="primary" @click="getFileList(currentTarget)">查看报告</Button>
        </div>
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="90">



<!--          currentTarget.type === 1 ? '攻击' : '防御'  ，防御的话，只能选择是-->
          <FormItem label="选择漏洞" v-if="[1,2,3].includes(hwTypeExtension)&&currentTarget.type === 1">
            <RadioGroup v-model="formValidate.vulnerability" @on-change="chageVulnerability" >
					    <Radio :label='1'>是</Radio>
					    <Radio :label='2'>否</Radio>
				    </RadioGroup>
          </FormItem>

<!--          防御-->
          <FormItem label="选择漏洞" v-if="[1,2,3].includes(hwTypeExtension)&&currentTarget.type !== 1" >
            <RadioGroup v-model="formValidate.vulnerability" @on-change="chageVulnerability" >
              <Radio :label='1'>是</Radio>
            </RadioGroup>
          </FormItem>
          <div class="content_border" v-for="(itemList,index) in formValidate.vulnerabilities" :key="index">
            <FormItem label="漏洞名称" prop="loopholeId" v-if="[1,2,3].includes(hwTypeExtension) && formValidate.vulnerability == 1">
             <Select filterable
              v-model="formValidate.loopholeId"
              filterable
              placeholder="漏洞名称"
              @on-change="changeThreatType"
            >
              <Option
                v-for="(item,index) in productVulnerabilityList"
                :value="item.id"
                :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem 
            label="漏洞名称"
            v-if="[1,2,3].includes(hwTypeExtension) && formValidate.vulnerability == 2"
            :prop="'vulnerabilities.' + index + '.threatType'"
            :rules="ruleValidate.threatType"
            >
            <Input
              v-model="itemList.threatType"
              clearable
              show-word-limit
              :maxlength="32"
              placeholder="漏洞名称"
              ></Input>
          </FormItem>
          <FormItem label="CVssV2" prop="CVssV2" v-if="[1,2,3].includes(hwTypeExtension)">
            <Input
              show-word-limit
              :maxlength="32"
              v-model="itemList.loopholeCvssv2"
              clearable
              :disabled="formValidate.vulnerability == 1"
              placeholder="CVssV2"
              ></Input>
          </FormItem>
          <FormItem label="CVE" prop="CVE" v-if="[1,2,3].includes(hwTypeExtension)">
            <Input
              show-word-limit
              :maxlength="32"
              v-model="itemList.loopholeCve"
              clearable
              :disabled="formValidate.vulnerability == 1"
              placeholder="CVE"
              ></Input>
          </FormItem>
          <FormItem label="CWE" prop="CWE" v-if="[1,2,3].includes(hwTypeExtension)">
            <Input
              show-word-limit
              :maxlength="32"
              v-model="itemList.loopholeCwe"
              clearable
              :disabled="formValidate.vulnerability == 1"
              placeholder="CWE"
              ></Input>
          </FormItem>
          <FormItem label="TVID" prop="TVID" v-if="[1,2,3].includes(hwTypeExtension)">
            <Input
              show-word-limit
              :maxlength="32"
              v-model="itemList.loopholeTvid"
              clearable
              :disabled="formValidate.vulnerability == 1"
              placeholder="TVID"
              ></Input>
          </FormItem>
          <FormItem label="CNNVD" prop="CNNVD" v-if="[1,2,3].includes(hwTypeExtension)">
            <Input
              show-word-limit
              :maxlength="32"
              v-model="itemList.loopholeCnnvd"
              clearable
              :disabled="formValidate.vulnerability == 1"
              placeholder="CNNVD"
              ></Input>
          </FormItem>
          <FormItem label="复现方式" prop="step" v-if="[1,2,3].includes(hwTypeExtension)">
            <Input
              show-word-limit
              :maxlength="64"
              v-model="itemList.step"
              clearable
              placeholder="复现方式"
              ></Input>
          </FormItem>
          <FormItem label="修复建议" prop="sulotion" v-if="[1,2,3].includes(hwTypeExtension)">
            <Input
              show-word-limit
              :maxlength="64"
              v-model="itemList.sulotion"
              clearable
              placeholder="修复建议"
              ></Input>
          </FormItem>
          </div>
          <div class="btn_add_style">
            <Button type="primary" icon="md-add" @click="handleAdd" v-if="formValidate.vulnerability == 2"></Button>
            <Button type="primary" icon="md-remove" @click="handleRemove" style="margin-left:5px" v-if="formValidate.vulnerabilities.length>1"></Button>
          </div>
          <FormItem
            v-if="currentTarget.type === 1"
            label="攻击类别"
            prop="attackType"
            key="attackType"
          >
            <!-- <Cascader
              :render-format="renderFormat"
              transfer
              :data="attackList"
              v-model="formValidate.attackType"
              placeholder="请选择攻击类型"
              filterable
              clearable
            ></Cascader> -->
            <Select filterable
              v-model="formValidate.attackType"
              filterable
              placeholder="攻击类别"
              @on-change="changeAttackType"
            >
              <Option
                :value="item.category"
                v-for="item in attackList"
                :key="item.id"
                :title="item.category"
                >{{ item.category }}</Option
              >
            </Select>
          </FormItem>
          <FormItem
            v-if="currentTarget.type === 2"
            label="防守类别"
            prop="defenseType"
            key="defenseType"
          >
            <!-- <Cascader
              :render-format="renderFormat"
              transfer
              :data="attackList"
              v-model="formValidate.attackType"
              placeholder="请选择攻击类型"
              filterable
              clearable
            ></Cascader> -->
            <Select filterable
              v-model="formValidate.defenseType"
              filterable
              placeholder="防守类别"
              @on-change="changeAttackType"
            >
              <Option
                :value="item.category"
                v-for="item in defenseList"
                :key="item.id"
                :title="item.category"
                >{{ item.category }}</Option
              >
            </Select>
          </FormItem>
<!--          .currentTarget.type === 1 ? '攻击类型' : '防守类型'-->
          <FormItem :label="currentTarget.type !== 1 ? '防守类型' : '攻击类型'" prop="attackLevel" key="attackLevel">
            <Select filterable
              v-model="formValidate.attackLevel"
              @on-change="changeAttackLevel"
              filterable
              :placeholder="currentTarget.type !== 1 ? '防守类型' : '攻击类型'"
            >
              <Option
                :value="item.mold"
                v-for="item in attackLevelList"
                :key="item.id"
                :title="item.mold"
                >{{ item.mold }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="类别" prop="targetType" key="targetType"  v-if="avaiRuleList.length > 1">
            <RadioGroup v-model="formValidate.targetType" type="button">
              <Radio v-for="item in avaiRuleList" :label="item.targetType" :key="item.id">{{
                item.targetType === '1' ? '一类' : item.targetType === '2' ? '二类' : '三类'
              }}</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="危险等级" prop="level" key="level" v-if="currentTarget.type === 1">
            <!--  && formValidate.level -->
            <RadioGroup v-model="formValidate.level" type="button">
              <Radio label="high">高危</Radio>
              <!-- :disabled="true" -->
              <Radio label="middle">中危</Radio>
              <Radio label="low">低危</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="审核意见" prop="approvalInfo" key="approvalInfo">
            <Input
              v-model.trim="formValidate.approvalInfo"
              clearable
              type="textarea"
              :maxlength="1000"
              :autosize="{ minRows: 4, maxRows: 8 }"
              placeholder="审核意见"
            ></Input>
            <!-- <my-quill-editor
              v-model="formValidate.approvalInfo"
              :maxLength="500000"
              :showNumberTip="false"
              :showParseTip="false"
              ref="myQuillEditor"
            ></my-quill-editor> -->
          </FormItem>
          <!--<FormItem label="分数：" prop="score">-->
          <!--<InputNumber :min="0" :step="1" v-model="formValidate.score"></InputNumber>-->
          <!--</FormItem>-->
          <FormItem label="结果" prop="status" key="status">
            <RadioGroup v-model="formValidate.status" @on-change="changeStatus" type="button">
              <Radio label="2">通过</Radio>
              <Radio label="3">驳回</Radio>
              <Radio label="4">挂起</Radio>
            </RadioGroup>
          </FormItem>
          <!-- 未审核的攻击报告，是否下线为“是”时，需要展示是否下线一栏 -->
<!--          checkedRule.line 切换危害程度时，自动查找关联的计分规则 已经下线了 line=true-->
<!--          currentTarget.type === 1 , 1 攻击报告 ，2防御报告-->
<!--          targetAvailable 审核目标是否下线-->
          <div style="display: none;height: 0;width: 0">
            checkedRule.line----{{checkedRule.line}}--
            currentTarget.type-- {{currentTarget.type}}--
            targetAvailable ---{{targetAvailable}}--
          </div>

          <FormItem
            label="下线目标"
            prop="line"
            key="line"
            v-if="checkedRule.line && currentTarget.type === 1 && targetAvailable"
          >
            <RadioGroup v-model="formValidate.line" type="button">
              <Radio label="1">是</Radio>
              <Radio label="0">否</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="将挂起原因同步给选手" prop="tag" key="tag" v-if="formValidate.status == 4">
            <RadioGroup v-model="formValidate.tag" type="button">
              <Radio label="1">是</Radio>
              <Radio label="0">否</Radio>
            </RadioGroup>
          </FormItem>
          <!-- :disabled="currentRule && currentRule.way === 'auto'" -->
          <FormItem label="分值" prop="score" key="score" v-if="formValidate.status === '2'">
            <InputNumber
              :min="0"
              :step="1"
              v-model="formValidate.score"
              placeholder="请输入分值"
            ></InputNumber>
            <Alert
              type="warning"
              show-icon
              v-show="currentRule && currentRule.description && formValidate.status === '2'"
              class="points-tip"
              >分值标准：{{ currentRule.description }}</Alert
            >
          </FormItem>
          <!-- <FormItem
            :label="this.formValidate.type === 1 ? '防守方扣分：' : '防守方得分：'"
            prop="score"
            v-if="formValidate.status === '2'"
          >
            <Input
              :disabled="currentRule.way === 'auto'"
              v-model="currentRule.score"
              number
              :placeholder="`请输入${this.formValidate.type === 1 ? '扣' : '得'}分值`"
              class="points-number"
            ></Input>
            <Alert
              type="warning"
              show-icon
              v-show="currentRule.description && formValidate.status === '2'"
              class="points-tip"
              >{{ this.formValidate.type === 1 ? '扣分标准：' : '得分标准：'
              }}{{ currentRule.description }}</Alert
            >
          </FormItem> -->
          <FormItem>
            <Button type="primary" @click="saveReport('formValidate')" :loading="submitBtnLoad"
              >确定</Button
            >
          </FormItem>
        </Form>
      </div>
    </Modal>
    <!--上传文件-->
    <Modal
      v-model="uploadModal"
      :mask-closable="false"
      width="500"
      :footer-hide="true"
      title="上传文件"
    >
      <Form ref="creatFormValidate" :model="creatFormValidate" :label-width="100">
        <FormItem label="上传文件" prop="file">
          <Upload
            ref="uploadIcon"
            v-model="creatFormValidate.file"
            :action="upLoadIconUrl"
            :multiple="false"
            :before-upload="handleUploadIcon"
          >
            <Button icon="ios-cloud-upload-outline">选择文件</Button>
          </Upload>
          <div v-if="creatFormValidate.file !== null">
            文件名称: {{ creatFormValidate.file.name }}
          </div>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="creatIconHandleSubmit()" :loading="uploadLoading"
            >确定</Button
          >
          <Button style="margin-left: 8px" @click="cancleUpload">取消</Button>
        </FormItem>
      </Form>
    </Modal>
    <package-progress
      :show="showProgress"
      :progress="progress"
      :status="progressStatus"
      @change="change"
      title="下载进度"
    ></package-progress>
    <Modal
      v-model="targetReportModal.show"
      :title="targetReportModal.title"
      width="1000px"
      footer-hide
    >
      <div class="flex-between">
        <div>
          <!-- <Input
            v-model.trim="targetReportModal.query.targetName"
            placeholder="目标"
            clearable
            style="width:120px; margin-left: 8px"
            @on-change="debounceSearchTargetReport"
          ></Input> -->
          <Select filterable
            v-model="targetReportModal.query.status"
            placeholder="审核状态"
            clearable
            style="width:120px;"
            @on-change="changeTargetReportPage(1)"
          >
            <Option value="1">未审核</Option>
            <Option value="2">已通过</Option>
            <Option value="3">已驳回</Option>
            <Option value="4">已挂起</Option>
            <Option value="5">驳回后再提交</Option>
          </Select>
        </div>
        <Page
          :total="targetReportModal.total"
          @on-change="changeTargetReportPage"
          show-total
          :page-size="targetReportModal.query.pageSize"
          :current="targetReportModal.query.page"
        />
      </div>
      <Table :border="true" :columns="targetReportModal.col" :data="targetReportModal.list"></Table>
    </Modal>
  </div>
</template>
<script>
import {
  refereeList,
  reportList,
  reportFileData,
  reviewReport,
  downloadReportsNew,
  downloadReports,
  downloadReportRecord,
  taskList,
  downloadTarget
} from '@/api/referee.js';
import {
  getTopoTargetInfo,
  queryHWAttackTypes,
  queryHWScoreRule,
  getDeclareCompanyList,
  lineTarget,
  getTopoTargetList
} from '@/api/drill_compete.js';
import {
  getProductVulnerability, // 获取漏洞
} from '@/api/product.js';
import { getaccessgrouplist } from '@/api/access_new';
import defenseFile from './defenseFile.vue';
// import screenRecord from './screenRecord.vue';
import PackageProgress from '@/components/package-progress/package-progress.vue';
import { allDirection } from '@/api/dict';
import LevelMixin from '@/mixin/levelMixin';
import { mapState } from 'vuex';
import { debounce } from '@/libs/utils';
import MyQuillEditor from '@/components/my-quill-editor';
import AuditLog from './auditLog';
import {checkTaskList} from "../../api/train";
export default {
  components: { defenseFile, PackageProgress, MyQuillEditor, AuditLog }, //screenRecord
  mixins: [LevelMixin],
  props:{
    extension:{
      type: Object,
      default:()=>{}
    },
    hwTypeExtension:{ // 1实网 2众测  3仿真
      type:Number,
      default:()=> 0
    }
  },
  name:'reportPage',
  data() {
    const validatePoints = (rule, value, callback) => {
      if (value || value === 0) {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入整数'));
        } else {
          if (value < 0 || value > 100000) {
            callback(new Error('分值范围0~100000'));
          } else {
            callback();
          }
        }
      } else {
        callback(new Error('不能为空'));
      }
    };
    const validateName = (rule, value, callback) => {
       let reg = /^[^/:*?"<>,|]{1,64}$/;
       if (!value) {
         callback(new Error('不能为空'));
         return;
       }
       if (!reg.test(value)) {
         callback(new Error('不能包含下列任意英文字符: / : * ? " < > , |，长度为1-64个字符'));
         return;
       }
       callback();
    };
    return {
      reflist:[],
      checkedRule: {},
      reportName1: '',
      groupName1: [],
      targetName: [],
      searchCheckTime: [],
      searchUploadTime: [],
      publicTarget: '',
      defenseTypes: [],
      attackLevel: [],
      currentTarget: {},
      progressStatus: 'active',
      progress: 0,
      showProgress: false, // 展示进度
      downloading: false,
      downloading1: false,
      downloading2: false,
      recordDownloading: false,
      targetDownloading: false,
      searchDownloading: false,
      currentFileId: '',
      level: '',
      industry: '',
      industryList: [],
      attackType: '',
      attackList: [],
      defenseList: [],
      ruleList: [],
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      contentHei: 'auto',
      // 工程 任务 id
      projectId: '',
      taskId: '',
      taskName: '',
      // 报告列表
      dataTotal: 0,
      targetAvailable:false,// 报告目标是否可以用
      reportList: [],
      reportCol: [
        //                  {
        //                      type:'index',
        //                      width:60,
        //                  },
        {
          title: '报告名称',
          key: 'reportName',
          width: 200,
          placement: 'top-left',
          tooltip: true
        },
        {
          title: '场景名称',
          key: 'testName',
          width: 200,
          placement: 'top-left',
          tooltip: true
        },
        {
          title: '漏洞名称',
          key: 'businessLoopholeName',
          width: 200,
          placement: 'top-left',
          tooltip: true
        },
        {
          title: 'CVssV2',
          key: 'businessLoopholeCvssv2',
          width: 200,
          placement: 'top-left',
          tooltip: true
        },
        {
          title: 'CVE',
          key: 'businessLoopholeCve',
          width: 200,
          placement: 'top-left',
          tooltip: true
        },
        {
          title: 'CWE',
          key: 'businessLoopholeCwe',
          width: 200,
          placement: 'top-left',
          tooltip: true
        },
        {
          title: 'TVID',
          key: 'businessLoopholeTvid',
          width: 200,
          placement: 'top-left',
          tooltip: true
        },
        {
          title: 'CNNVD',
          key: 'businessLoopholeCnnvd',
          width: 200,
          placement: 'top-left',
          tooltip: true
        },
        {
          title: '目标',
          key: 'targetName',
          width: 100,
          tooltip: true
        },
        {
          title: '团队名称',
          key: 'groupName',
          width: 100,
          tooltip: true
        },
        {
          title: '危险等级',
          key: 'level',
          width: 100,
          tooltip: true,
          render: (h, params) => {
            let obj = this.mixinPaserLevel(params.row.level);
            return h(
              'span',
              {
                style: {
                  color: obj.color
                }
              },
              obj.text
            );
          }
        },
        {
          title: '攻击类别',
          key: 'attackTypeName',
          width: 100,
          tooltip: true
        },
        {
          title: '防守类别',
          key: 'defenseType',
          width: 100,
          tooltip: true,
          render: (h, params) => {
    
            let defenseType = params.row.defenseType
            let str = '-'
            this.defenseList.forEach(item=>{
              if(item.id===defenseType){
                str = item.category
              }
            })
            
            return h(
                'span',
                str
            );
          }
        },
        {
          title: '攻击/防守类型',
          key: 'attackLevelName',
          align: 'center',
          width: 150,
          tooltip: true
        },
        {
          title: '目标类别',
          key: 'category',
          align: 'center',
          width: 150,
          tooltip: true,
          render: (h, params) => {
            return h(
              'span',
              params.row.category === '1' ? '一类' : params.row.category === '2' ? '二类' : '三类'
            );
          }
        },
        {
          title: '分值',
          key: 'score',
          width: 80,
          tooltip: true
        },
        // {
        //   title: '防守方扣分',
        //   key: 'score1',
        //   align: 'center',
        //   width: 80,
        //   tooltip: true,
        //   render: (h, params) => {
        //     return h('span', params.row.type !== 2 ? params.row.score : '');
        //   }
        // },
        // {
        //   title: '防守方得分',
        //   key: 'score2',
        //   align: 'center',
        //   width: 80,
        //   tooltip: true,
        //   render: (h, params) => {
        //     return h('span', params.row.type === 2 ? params.row.score : '');
        //   }
        // },
        {
          title: '单位',
          key: 'company',
          width: 100,
          tooltip: true
        },

        // {
        //   title: '防守类型',
        //   key: 'defenseTypeName',
        //   width: 100,
        //   tooltip: true
        // },
        {
          title: '任务名称',
          key: 'taskName',
          width: 100,
          tooltip: true
        },
        // {
        //   title: '报告类型',
        //   key: 'type',
        //   placement: 'top-right',
        //   width: 60,
        //   render: (h, params) => {
        //     return h('span', params.row.type === 2 ? '防御报告' : '攻击报告');
        //   }
        // },
        // {
        //   title: '报告文件',
        //   key: 'reportFile',
        //   placement: 'top-right',
        //   render: (h, params) => {
        //     return h('div', [
        //       h(
        //         'Button',
        //         {
        //           props: {
        //             type: 'primary',
        //             size: 'small'
        //           },
        //           on: {
        //             click: () => {
        //               this.getFileList(params.row);
        //             }
        //           }
        //         },
        //         '查看'
        //       )
        //     ]);
        //   }
        // },
        {
          title: '审核状态',
          key: 'status',
          placement: 'top-right',
          width: 80,
          render: (h, params) => {
            let color = '';
            let text = '';
            let status = params.row.status ? params.row.status : 1;
            if (status === 3) {
              color = 'error';
              text = '已驳回';
            } else if (status === 2) {
              color = 'success';
              text = '已通过';
            } else if (status === 1) {
              color = 'primary';
              text = '未审核';
            } else if (status === 4) {
              color = 'default';
              text = '已挂起';
            } else if (status === 5) {
              color = 'primary';
              text = '驳回后再提交';
            }
            return h('span', [
              h(
                'Tag',
                {
                  props: {
                    //                                      type:'dot',
                    color: color
                  }
                },
                text
              )
            ]);
          }
        },
        {
          title: '最后审核人',
          key: 'userName',
          width: 200,
          tooltip: true
        },
        {
          title: '审核意见',
          key: 'approvalInfo',
          width: 200,
          tooltip: true
        },
        {
          title: 'URL',
          key: 'url',
          width: 100,
          tooltip: true
        },
        {
          title: '提交人',
          key: 'creatorName',
          width: 100,
          tooltip: true
        },
        {
          title: '提交时间',
          key: 'createTime',
          width: 200,
          tooltip: true
        },
        {
          title: '报告文件',
          key: 'reportFile',
          placement: 'top-right',
          fixed:'right',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.getFileList(params.row);
                    }
                  }
                },
                '查看'
              )
            ]);
          }
        },
        {
          title: '审核日志',
          key: 'log',
          placement: 'top-right',
          fixed:'right',
          render: (h, params) => {
            return h(AuditLog, {
              props:{
                ruleList:this.ruleList,
                smallBtn:true,
                sceneId:this.sceneId,
                projectId:this.projectId,
                id:params.row.id
              }
            });
          }
        },
        {
          title: '审核',
          align: 'center',
          key: 'action',
          width: 120,
          placement: 'top-right',
          fixed:'right',
          // opList:[
          //   {
          //     txt:(data) => {
          //       let status = data.status ? data.status : 1;
          //       return status === 1 ? '审核' : '重新审核'
          //     },
          //     on: {
          //       click: (data) => {
          //         let status = data.status ? data.status : 1;
          //         status === 1 ? this.reviewBtn(data) : this.modifyReviewBtn(data);;
          //       }
          //     }
          //   }
          // ],
          render: (h, params) => {
            let status = params.row.status ? params.row.status : 1;
            let arr = [];
            if (status === 1) {
              arr.push(
                h(
                  'Button',
                  {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    on: {
                      click: () => {
                        this.reviewback=null
                        this.reviewBtn(params.row);
                      }
                    }
                  },
                  '审核'
                )
              );
            } else if (status === 2) {
              arr.push(
                h(
                  'Button',
                  {
                    props: {
                      type: 'success',
                      size: 'small'
                    },
                    on: {
                      click: () => {
                        this.modifyReviewBtn(params.row);
                      }
                    }
                  },
                  '重新审核'
                )
                // h('Button', {
                //     props: {
                //         type: 'info',
                //         size: 'small',
                //     },
                //     style:{
                //         marginLeft:'8px'
                //     },
                //     on: {
                //         'click': ()=>{
                //             this.uploadFile(params.row)
                //         },
                //     }
                // }, '补充报告文件')
              );
            } else if ([3, 4, 5].includes(status)) {
              arr.push(
                h(
                  'Button',
                  {
                    props: {
                      type: 'info',
                      size: 'small'
                    },
                    on: {
                      click: () => {
                        this.modifyReviewBtn(params.row);
                      }
                    }
                  },
                  '重新审核'
                )
              );
            }
            return h('div', arr);
          }
        }
      ],
      // 报告文件列表
      reportName: '',
      fileModal: false,
      fileList: [],
      defeFileList: [],
      attackFileList: [],
      connectRecords: [],
      fileCol: [
        {
          type:this.extension.hwType==2?'':'expand' ,
          width: 50,
          render: (h, params) => {
            if (this.extension.hwType!=2&&!this.extension.vpn) {
              return h('div', [
              h(defenseFile, {
                props: {
                  // row: this.defeFileList
                  row: this.currentType == 2 ? this.attackFileList : this.defeFileList,
                  type: this.currentType,
                }
              })
            ]);
            }else{
              console.log('2');
              return null
            }
          }
        },
        {
          type: 'index',
          width: 60
        },
        {
          title: '文件名称',
          key: 'name'
        },
        {
          title: '提交人',
          key: 'creatorName'
        },
        {
          title: '人员类型',
          key: 'userType'
        },
        {
          title: '操作',
          key: 'action',
          width: 180,
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small',
                    loading: this.downloading2 && this.currentFileId === params.row.id
                  },
                  on: {
                    click: () => {
                      this.downLoadFile(params.row);
                    }
                  }
                },
                '下载'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginLeft: '5px'
                  },
                  on: {
                    click: () => {
                      //新的预览接口
                      window.openTrain(`/api/minio/filePreview?id=${params.row.id}`);
                    }
                  }
                },
                '预览'
              )
            ]);
          }
        }
      ],
      // 审核报告
      reportID: '',
      reviewReportModal: false,
      extent4InjuryData: [],
      extent4DefenseTypesData: [],
      reviewback:null,
      formValidate: {
        vulnerability:2,
        threatType:'',
        // attackMeans:{},
        loopholeId:'',
        loopholeName:'',
        loopholeCvssv2:'',
        loopholeCve:'',
        loopholeCwe:'',
        loopholeTvid:'',
        loopholeCnnvd:'',
        attackType: '',
        approvalInfo: '',
        status: '',
        attackLevel: '',
        defenseType: '',
        targetType: '',
        level: '',
        score: 0,
        tag: '0',
        step:'',
        sulotion:'',
         // 存储漏洞数据的数组
        vulnerabilities:[{
          threatType:'',
          loopholeCvssv2:'',
          loopholeCve:'',
          loopholeCwe:'',
          loopholeTvid:'',
          loopholeCnnvd:'',
          step:'',
          sulotion:'',
        }]
      },
      ruleValidate: {
        loopholeId: [
          { required: true, message: '请选择漏洞', trigger: 'change' },
        ],
        threatType: [
          { required: true, validator: validateName, trigger: 'change' },
        ],
        attackType: [
          { required: true, message: '请选择攻击类型', trigger: 'change' }],
        attackLevel: [{ required: true, message: '请选择危害程度', trigger: 'change' }],
        defenseType: [{ required: true, message: '请选择防守类型', trigger: 'change' }],
        targetType: [{ required: true, message: '请选择目标类型', trigger: 'change' }],
        approvalInfo: [
          { required: true, min: 1, message: '请填写审核意见', trigger: 'change' }
          // { type: 'string', min: 20, message: '审核意见最少输入20个字符', trigger: 'change' }
        ],
        status: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
        // level: [{ required: true, message: '请选择危险等级', trigger: 'change' }],
        score: [{ required: true, type: 'number', validator: validatePoints, trigger: 'change' }],
        tag: [{ required: true, trigger: 'change',message:'请选择是否将挂起原因同步给选手' }]
      },
      submitBtnLoad: false,
      // 上传文件
      uploadLoading: false,
      uploadModal: false,
      upLoadIconUrl: `${this.baseURL}/referee/referee/upload`,
      creatFormValidate: {
        file: null
      },
      // 过滤
      businessLoopholeName:'',
      businessLoopholeOtherIds:'',
      serchProjectName: '',
      serchSceneName: '',
      serchTaskName: '',
      serchOther:{ // 23209 // 攻击击成果名称、提报人，攻击成果地址url、审核人
        url:'',
        creatorName:'',
        userName:'',
        userId:''

      },


      reportPage: 1,
      pageSize: 10,
      statusModel: [],
      attackStartTime: '',
      attackEndTime: '',
      currentType: '',
      type: '',
      company: '',
      companyList: [],
      taskList: [],
      isCheckFirst: false,
      // 靶标攻击报告
      targetReportModal: {
        show: false,
        title: '被攻击记录',
        list: [],
        total: 0,
        query: {
          page: 1,
          pageSize: 10,
          targetName: '',
          level: '',
          status: ''
        },
        col: [
          {
            title: '报告名称',
            key: 'reportName',
            tooltip: true
            // render: (h, params) => {
            //   return h(
            //     'Tooltip',
            //     {
            //       style: {
            //         width: '100%'
            //       },
            //       props: {
            //         content: params.row.reportName,
            //         transfer: true
            //       }
            //     },
            //     [
            //       h(
            //         'a',
            //         {
            //           class: 'text-ellipsis',
            //           style: {
            //             width: '100%'
            //           },
            //           attrs: {
            //             href: '/api/minio/download/' + params.row.fileId,
            //             download: ''
            //           }
            //         },
            //         params.row.reportName
            //       ),
            //       h(
            //         'span',
            //         {
            //           slot: 'content'
            //         },
            //         params.row.reportName
            //       )
            //     ]
            //   );
            // }
          },
          {
            title: '攻击队伍',
            key: 'groupName',
            width: 200,
            tooltip: true
          },
          {
            title: '攻击时间',
            key: 'createTime',
            width: 180
          },
          {
            title: '审核状态',
            key: 'status',
            placement: 'top-right',
            render: (h, params) => {
              let color = '';
              let text = '';
              let status = params.row.status ? params.row.status : 1;
              if (status === 3) {
                color = 'error';
                text = '已驳回';
              } else if (status === 2) {
                color = 'success';
                text = '已通过';
              } else if (status === 1) {
                color = 'primary';
                text = '未审核';
              } else if (status === 4) {
                color = 'default';
                text = '已挂起';
              } else if (status === 5) {
                color = 'primary';
                text = '驳回后再提交';
              }
              return h('span', [
                h(
                  'Tag',
                  {
                    props: {
                      //                                      type:'dot',
                      color: color
                    }
                  },
                  text
                )
              ]);
            }
          },
          {
            title: '得分',
            key: 'score',
            tooltip: true,
            render: (h, params) => {
              return h(
                'span',
                params.row.score || params.row.score === 0 ? params.row.score : '-'
              );
            }
          },
          {
            title: '操作',
            key: 'action',
            width: 140,
            render: (h, params) => {
              return h('div', [
                h(
                  'Button',
                  {
                    props: {
                      type: 'primary',
                      size: 'small'
                    }
                  },
                  [
                    h(
                      'a',
                      {
                        attrs: {
                          href: `/api/minio/download/${params.row.fileId}`
                        },
                        style: {
                          color: '#fff'
                        }
                      },
                      '下载'
                    )
                  ]
                ),
                h(
                  'Button',
                  {
                    props: {
                      type: 'primary',
                      size: 'small'
                    },
                    style: {
                      marginLeft: '5px'
                    },
                    on: {
                      click: () => {
                        //新的预览接口
                        window.openTrain(`/api/minio/filePreview?id=${params.row.fileId}`);
                      }
                    }
                  },
                  '预览'
                )
              ]);
            }
          }
        ]
      },
      targetData: [],
      groupData: [],
      // 漏洞数据
      productVulnerabilityList:[],
      currentVulnerability:{}, // 选择的漏洞信息
     };
  },
  computed: {
    pointsTip() {
      let valList, templateList, template;
      if (this.formValidate.type === 1) {
        valList = this.formValidate.attackLevel;
        templateList = this.attackLevelList;
      } else {
        valList = this.formValidate.defenseType;
        templateList = this.defenseTypesList;
      }
      valList = valList || [''];
      let val = valList[valList.length - 1];
      if (!val) {
        return '';
      }
      template = templateList.find((item) => item.dictid === val);
      return template && template.memo;
    },
    reviewReportTitle() {
      if (this.currentTarget.id) {
        return `审核${this.currentTarget.type === 1 ? '攻击' : '防御'}报告 ${
          this.currentTarget.targetName
        }`;
      } else {
        // 未选定当前的审核报告数据，给一个默认的title
        return '审核报告';
      }
    },
    attackLevelList() {
      if (!this.formValidate.attackType && !this.formValidate.defenseType) {
        return [];
      }
      let list = this.currentTarget.type === 1 ? this.attackList : this.defenseList;
      let type =
        this.currentTarget.type === 1
          ? this.formValidate.attackType
          : this.formValidate.defenseType;
      return list.find((item) => item.value === type).children;
    },
    currentRule() {
      if (this.avaiRuleList.length === 1) {
        return this.avaiRuleList[0];
      } else if (this.avaiRuleList.length > 1 && this.formValidate.targetType) {
        return this.avaiRuleList.find((item) => item.targetType === this.formValidate.targetType);
      } else {
        return {
          id: ''
        };
      }
    },
    avaiRuleList() {
      let category =
        this.currentTarget.type === 1
          ? this.formValidate.attackType
          : this.formValidate.defenseType;
      if (!(category && this.formValidate.attackLevel)) {
        return [];
      }
      let contrapose = this.currentTarget.type === 1 ? '2' : '1';
      let ruleList = this.ruleList.filter(
        (item) =>
          item.contrapose === contrapose &&
          item.category === category &&
          item.mold === this.formValidate.attackLevel
      );
      let avaiRuleList = ruleList.filter((rule) => rule.targetType === this.currentTarget.category);
      return avaiRuleList.length > 0 ? avaiRuleList : ruleList;
    },
    ...mapState('board', ['newNotice'])
  },
  watch: {
    newNotice(val, oldval) {
      if (val.sceneName) {
        if (val.sceneName === this.$route.query.sceneName) {
          this.getReportList();
        }
      }
    },
    currentRule(val, oldVal) {
      if (val && val.id && this.isCheckFirst) {
        //第一次不使用规则的信息回显
        // this.formValidate.level = val.grade;
        this.isCheckFirst = false;
        return;
      }
      if (val.id !== oldVal.id && val.id) {
        this.formValidate.score = val.score || 0;
        this.formValidate.level = val.grade;
        this.formValidate.description = val.description;
      } else {
      }
    },
    currentType(newValue) {
      return;
      if (newValue === 2 && this.fileCol[0].type === 'expand') {
        this.fileCol.shift();
      } else if (newValue === 1 && this.fileCol[0].type !== 'expand') {
        this.fileCol.unshift({
          type: 'expand',
          width: 50,
          render: (h, params) => {
            return h('div', [
              h(defenseFile, {
                props: {
                  row: this.currentType == 2 ? this.defeFileList : this.attackFileList,
                  type: this.currentType
                }
              })
              // h('div', {}, [
              //   h(
              //     'h3',
              //     {
              //       style: {
              //         margin: '10px 0'
              //       }
              //     },
              //     '攻击时间：' + this.attackStartTime + ' - ' + this.attackEndTime
              //   )
              // ]),
              // h(screenRecord, {
              //   props: {
              //     row: this.connectRecords
              //   }
              // })
            ]);
          }
        });
      }
    }
  },
  created() {
    this.sceneId = this.$route.query.sceneId;
    this.sceneName = this.$route.query.sceneName;
    this.projectId = this.$route.query.projectId;
    this._targetReportQuery = { ...this.targetReportModal.query };
  },
  async mounted() {
    this.getRefereeList()
    this.getDeclareCompanyList();
    this.getAccessGroupList();
    this.getAllTargetTeam();
    await this.getTaskList();
    // await this.getIndustryTypes();
    await this.queryHWScoreRule();
    // await this.getHwAttackLevelTypes();
    // await this.getHwDefenseTypes();
    this.getReportList();
    if([1,2,3].includes(this.hwTypeExtension)){
      this.getProductVulnerability()
    }
    if(this.extension.hwType ==2 ){
      // 众测不需要展开信息，但是列表展示箭头 直接去掉这一项
      this.fileCol.shift()
    }
  },
  methods: {
    checkTaskList,
    getRefereeList(){
      let params = {
        sceneId:this.$route.query.sceneId
      }
      refereeList(params).then(res=>{
        console.log('==---裁判审核人员啊-==res',res);
        let reflist = []
        if(res.data.code ==1 && res.data.data){
          reflist = res.data.data||[]
        }else{
          this.$Message.error(res.message)
        }
        this.reflist = Array.from(new Set(reflist.map(item => item.id))).map(id =>
            reflist.find(item => item.id === id)
        );
      }).catch(error=>{
        console.log('error',error);
      })
    },

    // 创建漏洞信息
    handleAdd(){
      this.formValidate.vulnerabilities.push({
        threatType:'',
        loopholeCvssv2:'',
        loopholeCve:'',
        loopholeCwe:'',
        loopholeTvid:'',
        loopholeCnnvd:'',
        step:'',
        sulotion:'',
      })
    },

    // 删除
    handleRemove(){
      this.formValidate.vulnerabilities.pop()
    },
    // 切换漏洞
    chageVulnerability(val){

      // 只要是 切换了 选择，漏洞名称都数据清空 22274
      this.formValidate.loopholeId = '';
      this.currentVulnerability = {}
      this.formValidate.loopholeName = '';
      // this.formValidate.threatType = '';
      // this.formValidate.loopholeCvssv2 = '';
      // this.formValidate.loopholeCve = '';
      // this.formValidate.loopholeCwe = '';
      // this.formValidate.loopholeTvid = '';
      // this.formValidate. loopholeCnnvd = '';
       this.formValidate.vulnerabilities = [{
        threatType:'',
        loopholeCvssv2:'',
        loopholeCve:'',
        loopholeCwe:'',
        loopholeTvid:'',
        loopholeCnnvd:'',
        step:'',
        sulotion:'',
      }]

      if(this.reviewback && this.reviewback.vulnerability===val){ // 重新审核的时候，当前选的选择和备份一样 则数据复原 22274
        let row = this.reviewback
        this.$set(this.formValidate, 'loopholeId', row.loopholeId);
        this.$set(this.formValidate, 'loopholeName', row.loopholeName);
        this.formValidate.vulnerabilities = []
        // this.$set(this.formValidate.vulnerabilities[0], 'threatType', row.threatType);
        // this.$set(this.formValidate.vulnerabilities[0], 'loopholeCvssv2', row.loopholeCvssv2);
        // this.$set(this.formValidate.vulnerabilities[0], 'loopholeCve', row.loopholeCve);
        // this.$set(this.formValidate.vulnerabilities[0], 'loopholeCwe', row.loopholeCwe);
        // this.$set(this.formValidate.vulnerabilities[0], 'loopholeTvid', row.loopholeTvid);
        // this.$set(this.formValidate.vulnerabilities[0], 'loopholeCnnvd', row.loopholeCnnvd);
        this.setFormData(row, true)
        // if(this.reviewback.vulnerability===1){// 如果选择是，那么没有漏洞名称
        //   this.$set(this.formValidate.vulnerabilities[0], 'threatType', '');
        // }
        // return
      }
    },
  // 获取漏洞数据
    getProductVulnerability(){
      let params = {
        pageIndex:1,
        pageSize:9999999,
      }
      getProductVulnerability(params).then(res=>{
        // console.log('==----==res',res);
        if(res.code ==1){
          this.productVulnerabilityList = res.data.items
        }else{
          this.$Message.error(res.message)
        }
      }).catch(error=>{
        console.log('error',error);
      })
    },
    // 选择漏洞信息
    changeThreatType(val){
      console.log('===========',val,this.currentVulnerability);
      if(val){
        this.currentVulnerability = this.productVulnerabilityList.find(item => item.id === val) || {};
        this.formValidate.loopholeId = this.currentVulnerability.id;
        this.formValidate.loopholeName = this.currentVulnerability.name;
        // this.formValidate.loopholeCvssv2 = this.currentVulnerability.cvssv2;
        // this.formValidate.loopholeCve = this.currentVulnerability.cve;
        // this.formValidate.loopholeCwe = this.currentVulnerability.cwe;
        // this.formValidate.loopholeTvid = this.currentVulnerability.tvid;
        // this.formValidate. loopholeCnnvd = this.currentVulnerability.cnnvd;
        this.formValidate.vulnerabilities[0].loopholeCvssv2 = this.currentVulnerability.cvssv2;
        this.formValidate.vulnerabilities[0].loopholeCve = this.currentVulnerability.cve;
        this.formValidate.vulnerabilities[0].loopholeCwe = this.currentVulnerability.cwe;
        this.formValidate.vulnerabilities[0].loopholeTvid = this.currentVulnerability.tvid;
        this.formValidate.vulnerabilities[0]. loopholeCnnvd = this.currentVulnerability.cnnvd;
      }else{
        this.currentVulnerability = {}
        this.formValidate.loopholeId = '';
        this.formValidate.loopholeName = '';
        this.formValidate.vulnerabilities = [{
        threatType:'',
        loopholeCvssv2:'',
        loopholeCve:'',
        loopholeCwe:'',
        loopholeTvid:'',
        loopholeCnnvd:'',
        step:'',
        sulotion:'',
      }]
        // this.formValidate.loopholeCvssv2 = '';
        // this.formValidate.loopholeCve = '';
        // this.formValidate.loopholeCwe = '';
        // this.formValidate.loopholeTvid = '';
        // this.formValidate. loopholeCnnvd = '';
      }
    },
    // 切换审核结果时的操作
    changeStatus(type) {
      // 通过自动设值的报告时，自动设置一次分数
      if (type === '2') {
        this.formValidate.score = this.currentRule.score || 0;
      }
    },
    // 切换危害程度时，自动查找关联的计分规则，用于页面判断是否需要展示“是否下线目标”一栏
    changeAttackLevel(mold) {
      if (!mold) {
        this.checkedRule = {};
      } else {
        this.checkedRule = this.ruleList.find((item) => item.mold === mold) || {};
      }
    },
    // 级联选择只展示叶子节点的内容
    renderFormat(label) {
      return label[label.length - 1];
    },
    // 湖里区任务列表
    getTaskList() {
      return new Promise((resolve, reject) => {
        let params = {
          page: 1,
          pageSize: 10000,
          testId: this.sceneId,
          status: 'running'
        };
        taskList(params)
          .then((res) => {
            if (res.data.code === 1) {
              this.taskList = res.data.data.pageData;
              if (this.taskList.length > 0) {
                this.taskId = this.taskList[0].id;
                this.taskName = this.taskList[0].name;
              }
              resolve();
            }
          })
          .catch((err) => {});
      });
    },
    changeAttackType() {
      this.formValidate.attackLevel = '';
      this.formValidate.targetType = '';
      this.formValidate.line = '';
      this.formValidate.tag = '0';
      this.formValidate.score = 0;
      this.formValidate.description = '';
      this.formValidate.level = '';
    },
    changeTask(id) {
      this.taskName = this.taskList.find((item) => item.id === id).name;
      this.refreshSceneList();
    },
    // 复原修锁条件
    refreshSceneList() {
      this.serchOther={
        url:'',
        creatorName:'',
        userName:'',
        userId:''
      }
      this.type = '';
      this.industry = '';
      this.attackType = '';
      this.defenseTypes = [];
      this.attackLevel = [];
      this.level = '';
      this.company = '';
      this.statusModel = [];
      this.pageSize = 10;
      this.current = 1;
      this.publicTarget = '';
      this.reportName1 = '';
      this.groupName1 = [];
      this.targetName = [];
      this.searchCheckTime = [];
      this.searchUploadTime = [];
      this.businessLoopholeName = ''
      this.businessLoopholeOtherIds = ''
      this.getReportList();
    },
    getDeclareCompanyList() {
      getDeclareCompanyList(this.projectId)
        .then(({ code, data, message }) => {
          if (code === 1) {
            this.companyList = data;
          } else {
          }
        })
        .catch((error) => {});
    },
    // 获取目标危害程度
    getHwAttackLevelTypes() {
      return new Promise((resolve) => {
        allDirection({ dictTypeID: 'hwAttackLevelTypes' })
          .then(({ code, message, attribute = {} }) => {
            attribute = attribute.attribute || [];
            if (code !== 1) {
              this.$Message.warning(message);
              return;
            }
            let list = [];
            attribute.forEach((item) => (list = list.concat(item.dictEntryList)));
            this.attackLevelList = list;
            let parentNodeList = list.filter((item) => item.parentid === '');
            this.extent4InjuryData = parentNodeList.map((item) => {
              let ret = {
                value: item.dictid,
                label: item.dictname,
                children: []
              };
              list.forEach((subItem) => {
                if (subItem.parentid === item.dictid) {
                  // 将二级的字典遍历查询出来
                  ret.children.push({
                    value: subItem.dictid,
                    label: subItem.dictname
                  });
                }
              });
              return ret;
            });
          })
          .catch(() => {
            this.$Message.error('获取目标危害程度列表异常');
          })
          .finally(() => {
            resolve();
          });
      });
    },
    // 获取目标危害程度
    getHwDefenseTypes() {
      return new Promise((resolve) => {
        allDirection({ dictTypeID: 'hwDefenseTypes' })
          .then(({ code, message, attribute = {} }) => {
            attribute = attribute.attribute || [];
            if (code !== 1) {
              this.$Message.warning(message);
              return;
            }
            let list = [];
            attribute.forEach((item) => (list = list.concat(item.dictEntryList)));
            this.defenseTypesList = list;
            let parentNodeList = list.filter((item) => item.parentid === '');
            this.extent4DefenseTypesData = parentNodeList.map((item) => {
              let ret = {
                value: item.dictid,
                label: item.dictname,
                children: []
              };
              list.forEach((subItem) => {
                if (subItem.parentid === item.dictid) {
                  // 将二级的字典遍历查询出来
                  ret.children.push({
                    value: subItem.dictid,
                    label: subItem.dictname
                  });
                }
              });
              return ret;
            });
          })
          .catch(() => {
            this.$Message.error('获取目标危害程度列表异常');
          })
          .finally(() => {
            resolve();
          });
      });
    },
    change(val) {
      this.showProgress = val;
    },
    downloadReportRecord() {
      if (this.dataTotal == 0) {
        this.$Message.info('当前数据为空');
        return;
      }
      this.recordDownloading = true;
      this.showProgress = true;
      let params = {
        taskId: this.taskId,
        statusList: this.statusModel,
        level: this.level,
        type: this.type,
        company: this.company,
        groupIds: this.groupName1,
        targets: this.targetName,
        reportName: this.reportName1
      };
      if (this.searchUploadTime.length == 2 && this.searchUploadTime[0]) {
        params.startTime = this.searchUploadTime[0] + ':00';
        params.endTime = this.searchUploadTime[1] + ':59';
      }
      if (this.searchCheckTime.length == 2 && this.searchCheckTime[0]) {
        params.applyStartTime = this.searchCheckTime[0] + ':00';
        params.applyEndTime = this.searchCheckTime[1] + ':59';
      }
      console.log(params);
      downloadReportRecord(this.sceneName, params, this.downFileProgress)
        .then(({ data }) => {
          this.total = 0;
          if (data.type == 'application/octet-stream') {
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(data);
            downloadElement.href = href;
            downloadElement.download = `${this.sceneName}-统计信息下载.xls`;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
            this.$Message.info('统计信息下载成功');
          } else {
            this.$Message.warning('统计信息下载失败');
          }
          this.recordDownloading = false;
        })
        .catch((error) => {
          his.progressStatus = 'wrong';
          this.$Message.error('统计信息下载异常');
          this.recordDownloading = false;
        })
        .finally(() => {
          this.progress = 100;
          setTimeout(() => {
            this.showProgress = false;
            this.progressStatus = 'active';
            this.progress = 0;
          }, 2000);
        });
    },
    // 打包下载攻击报告以及关联的防御报告
    downloadReports() {
      this.downloading1 = true;
      this.showProgress = true;
      let fileList =
        this.currentType == 1
          ? this.defeFileList.concat(this.fileList)
          : this.attackFileList.concat(this.fileList);
      downloadReports(
        this.taskId,
        fileList.map((item) => item.reportId),
        this.downFileProgress
      )
        .then(({ data }) => {
          this.total = 0;
          if (data.type == 'application/octet-stream') {
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(data);
            downloadElement.href = href;
            downloadElement.download = `${this.groupName}-${this.currentTargetName}-${this.reportName}关联报告打包下载.zip`;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
            this.$Message.info('报告下载成功');
          } else {
            this.$Message.warning('下载失败，不存在文件数据');
          }
          this.downloading1 = false;
        })
        .catch((error) => {
          his.progressStatus = 'wrong';
          this.$Message.error('下载异常');
          this.downloading1 = false;
        })
        .finally(() => {
          this.progress = 100;
          setTimeout(() => {
            this.showProgress = false;
            this.progressStatus = 'active';
            this.progress = 0;
          }, 2000);
        });
    },
    downloadReportsNew() {
      if (this.dataTotal == 0) {
        this.$Message.info('当前数据为空');
        return;
      }
      this.searchDownloading = true;
      this.showProgress = true;
      let params = {
        taskId: this.taskId,
        statusList: this.statusModel,
        level: this.level,
        type: this.type,
        company: this.company,
        groupIds: this.groupName1,
        targets: this.targetName,
        reportName: this.reportName1
      };
      if (this.searchUploadTime.length == 2 && this.searchUploadTime[0]) {
        params.startTime = this.searchUploadTime[0] + ':00';
        params.endTime = this.searchUploadTime[1] + ':59';
      }
      if (this.searchCheckTime.length == 2 && this.searchCheckTime[0]) {
        params.applyStartTime = this.searchCheckTime[0] + ':00';
        params.applyEndTime = this.searchCheckTime[1] + ':59';
      }
      console.log(params);
      downloadReportsNew(this.sceneName, params, this.downFileProgress)
        .then(({ data }) => {
          this.total = 0;
          if (data.type == 'application/octet-stream') {
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(data);
            downloadElement.href = href;
            downloadElement.download = `${this.taskName}.zip`;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
            this.$Message.info('报告下载成功');
          } else {
            this.$Message.warning('下载失败，不存在文件数据');
          }
          this.searchDownloading = false;
        })
        .catch((error) => {
          this.progressStatus = 'wrong';
          this.$Message.error('下载异常');
          this.searchDownloading = false;
        })
        .finally(() => {
          this.progress = 100;
          setTimeout(() => {
            this.showProgress = false;
            this.progressStatus = 'active';
            this.progress = 0;
          }, 2000);
        });
    },
    downloadTarget() {
      // let href = `/api/compete/topoTarget/exportTarget/${this.projectId}/${this.sceneName}`;
      // let a = document.createElement('a');
      // document.body.appendChild(a);
      // a.href = href;
      // a.download = ''; //命名下载名称
      // a.click(); //点击触发下载
      // a.remove();
      // return
      // if (this.dataTotal == 0) {
      //   this.$Message.info('当前数据为空');
      //   return;
      // }
      this.targetDownloading = true;
      this.showProgress = true;
      downloadTarget(this.projectId, this.sceneName, this.downFileProgress)
        .then(({ data }) => {
          this.total = 0;
          if (data.type == 'application/octet-stream') {
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(data);
            downloadElement.href = href;
            downloadElement.download = `${this.sceneName}-目标.xls`;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
            this.$Message.info('目标下载成功');
          } else {
            this.$Message.warning('下载失败，不存在数据');
          }
          this.targetDownloading = false;
        })
        .catch((error) => {
          this.progressStatus = 'wrong';
          this.$Message.error('下载异常');
          this.targetDownloading = false;
        })
        .finally(() => {
          this.progress = 100;
          setTimeout(() => {
            this.showProgress = false;
            this.progressStatus = 'active';
            this.progress = 0;
          }, 2000);
        });
    },
    //导出任务下的所有报告
    downloadAllReports() {
      if (this.reportList.length == 0) {
        this.$Message.info('当前页面数据为空');
        return;
      }
      this.downloading = true;
      this.showProgress = true;
      downloadReports(
        this.taskId,
        this.reportList.map((report) => report.id),
        this.downFileProgress
      )
        .then(({ data }) => {
          this.total = 0;
          if (data.type == 'application/octet-stream') {
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(data);
            downloadElement.href = href;
            downloadElement.download = `${this.taskName}.zip`;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
            this.$Message.info('报告下载成功');
          } else {
            this.$Message.warning('下载失败，不存在文件数据');
          }
          this.downloading = false;
        })
        .catch((error) => {
          this.progressStatus = 'wrong';
          this.$Message.error('下载异常');
          this.downloading = false;
        })
        .finally(() => {
          this.progress = 100;
          setTimeout(() => {
            this.showProgress = false;
            this.progressStatus = 'active';
            this.progress = 0;
          }, 2000);
        });
    },
    exportRank(isDefend) {
      let sceneId = this.sceneId;
      let sceneName = this.sceneName;
      let href = isDefend
        ? `/api/compete/teamScoreRecord/exportDe/${sceneId}/${sceneName}`
        : `/api/compete/teamScoreRecord/exportAt/${sceneId}/${sceneName}`;
      let a = document.createElement('a');
      document.body.appendChild(a);
      a.href = href;
      a.download = ''; //命名下载名称
      a.click(); //点击触发下载
      a.remove();
    },
    downFileProgress(progress) {
      let currentProgress = progress.loaded * 1; //B单位
      if (this.total) {
        this.total += currentProgress;
      } else {
        this.total = currentProgress;
      }
      currentProgress = this.total - currentProgress ? currentProgress : currentProgress / 2;
      let rate = (((this.total - currentProgress) / this.total) * 100).toFixed(2) * 1;
      if (!this.rate || rate > this.rate) {
        this.progress = rate;
      }
    },
    // 获取行列列表
    getIndustryTypes() {
      return new Promise((resolve) => {
        allDirection({ dictTypeID: 'hwIndustryTypes' })
          .then(({ code, message, attribute = {} }) => {
            attribute = attribute.attribute || [];
            if (code !== 1) {
              this.$Message.warning(message);
              return;
            }
            let list = [];
            attribute.forEach((item) => (list = list.concat(item.dictEntryList)));
            this.industryList = list;
          })
          .catch(() => {
            this.$Message.error('获取行业列表异常');
          })
          .finally(() => {
            resolve();
          });
      });
    },
    // 获取攻击类型列表
    getAttackTypes() {
      return new Promise((resolve, reject) => {
        // { contrapose: this.isTargetAdmin ? '1' : '2' }
        queryHWAttackTypes(this.sceneId, { contrapose: 2 })
          .then(({ code, data, message }) => {
            if (code == 1) {
              this.attackList = data;
              resolve();
            } else {
              this.$Message.error(message);
            }
          })
          .catch((error) => {
            console.log(error);
          });
      });
    },
    // getAttackTypes() {
    //     return new Promise(resolve => {
    //     allDirection({ dictTypeID: 'hwAttackTypes' }).then(({ code, message, attribute = {} }) => {
    //         attribute = attribute.attribute || []
    //         if (code !== 1) {
    //         this.$Message.warning(message)
    //         return
    //         }
    //         let list = []
    //         attribute.forEach(item => list = list.concat(item.dictEntryList))
    //         this.attackList = list
    //     }).catch(() => {
    //         this.$Message.error('获取攻击类型列表异常')
    //     }).finally(() => {
    //         resolve()
    //     })
    //     })
    // },
    queryHWScoreRule() {
      return new Promise((resolve, reject) => {
        let query = { pageIndex: 1, pageSize: 100000 };
        queryHWScoreRule(this.sceneId, query)
          .then(({ code, data, message }) => {
            if (code == 1) {
              this.ruleList = data.items;

              //攻击还是防御
              let ruleList = data.items;
              let ruleAttackObj = {};
              let ruleDefenseObj = {};
              ruleList.forEach((rule) => {
                if (rule.contrapose === '1') {
                  //防守
                  if (!ruleDefenseObj[rule.category]) {
                    ruleDefenseObj[rule.category] = {
                      ...rule,
                      label: rule.category,
                      value: rule.category,
                      children: [rule]
                    };
                  } else {
                    if (
                      !ruleDefenseObj[rule.category].children.find(
                        (item) => item.mold === rule.mold
                      )
                    ) {
                      ruleDefenseObj[rule.category].children.push(rule);
                    }
                  }
                } else {
                  if (!ruleAttackObj[rule.category]) {
                    ruleAttackObj[rule.category] = {
                      ...rule,
                      label: rule.category,
                      value: rule.category,
                      children: [rule]
                    };
                  } else {
                    if (
                      !ruleAttackObj[rule.category].children.find((item) => item.mold === rule.mold)
                    ) {
                      ruleAttackObj[rule.category].children.push(rule);
                    }
                  }
                }
              });
              this.attackList = Object.values(ruleAttackObj);
              this.defenseList = Object.values(ruleDefenseObj);
              resolve();
            } else {
              this.$Message.error(message);
            }
          })
          .catch((error) => {
            console.log(error);
          });
      });
    },
    // 修改模态框状态
    changeModalStatus(type) {
      if (!type) {
        this.$refs['formValidate'].resetFields();
      }
    },
    // 返回icon管理
    returnCompany() {
      this.$router.push({
        path: '/referee'
      });
    },
    getAllTargetTeam() {
      let params = {
        pageIndex: 1,
        pageSize: 2147483646,
        projectId: this.$route.query.projectId
      };
      getTopoTargetList(params).then((data) => {
        if (data.code == 1) {
          this.targetData = data.data.items;
        }
      });
    },
    getAccessGroupList() {
      let params = {
        pageIndex: 1,
        pageSize: 2147483647,
        testId: this.$route.query.sceneId
      };
      getaccessgrouplist(params).then((data) => {
        if (data.code == 1) {
          let accessGroupList = data.data.items.filter(
            (item) => item.name !== '目标方管理员组' && item.creatorName != '内部服务用户'
          );
          this.groupData = data.data.items;
        } else if (data.code == -2) {
          this.groupData = [];
        } else {
          this.$Message.warning(data.message);
        }
      });
    },
    // 报告列表
    getReportList() {
      if (!this.taskId) {
        this.reportList = [];
        return;
      }
      let serchOther = this.serchOther
      this.$nextTick(() => {
        let params = {
          ...serchOther,
          page: this.reportPage,
          pageSize: this.pageSize,
          taskId: this.taskId,
          statusList: this.statusModel,
          //   industry: this.industry,
          //   attackType: this.attackType,
          level: this.level,
          type: this.type,
          company: this.company,
          //   defenseType: this.defenseTypes.length
          //     ? this.defenseTypes[this.defenseTypes.length - 1]
          //     : undefined,
          //   publicTarget: this.publicTarget ? (this.publicTarget === '1' ? true : false) : undefined,
          //   attackLevel: this.attackLevel.length
          //     ? this.attackLevel[this.attackLevel.length - 1]
          //     : undefined,
          groupIds: this.groupName1,
          targets: this.targetName,
          reportName: this.reportName1,
        };
        if (this.searchUploadTime.length == 2 && this.searchUploadTime[0]) {
          params.startTime = this.searchUploadTime[0] + ':00';
          params.endTime = this.searchUploadTime[1] + ':59';
        }
        if (this.searchCheckTime.length == 2 && this.searchCheckTime[0]) {
          params.applyStartTime = this.searchCheckTime[0] + ':00';
          params.applyEndTime = this.searchCheckTime[1] + ':59';
        }
        if([1,2,3].includes(this.hwTypeExtension)){
          params.businessLoopholeName = this.businessLoopholeName
          params.businessLoopholeOtherIds = this.businessLoopholeOtherIds
        }
        this.requestReportList(params).then(({ list, total }) => {
          this.reportList = list;
          this.dataTotal = total;
        });
        return;
        reportList(params)
          .then((res) => {
            if (res.data.code === 1) {
              let getData = res.data.data;
              this.dataTotal = getData.totalCount;
              let list = getData.pageData;
              this.reportList = list.map((item) => {
                let type = item.type === 1 ? 'attackType' : 'defenseType';
                let currentRule = this.ruleList.find((rule) => rule.id === item[type]);
                item.attackTypeName = item.attackType && currentRule ? currentRule.category : '';
                item.attackLevelName = item.attackLevel;
                item.defenseTypeName = item.defenseType && currentRule ? currentRule.category : '';
                return item;
              });
            } else {
              this.$Message.warning(res.data.message);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      });
    },
    // 获取目标是否下线
    getTopoTargetInfo(id){

      this.targetAvailable = false // 目标是不可用 ，只有查寻出来报告目标是 targetAvailable = true ,才展示是否下线目标
      return new Promise((resolve, reject) => {
        getTopoTargetInfo(id)
          .then((res) => {
            if (res.code === 1) {
              let {available}  = res.data
              this.targetAvailable = available
            }
          })
      });
    },
    openTargetReportModal() {
      this.targetReportModal.query = { ...this._targetReportQuery };
      this.getTargetReportList();
    },
    getTargetReportList() {
      this.targetReportModal.show = true;
      let params = {
        ...this.targetReportModal.query,
        company: this.currentTarget.company,
        type: 1,
        target: this.currentTarget.target
      };
      this.requestReportList(params).then(({ list, total }) => {
        this.targetReportModal.list = list;
        this.targetReportModal.total = total;
      });
    },
    debounceSearchTargetReport: debounce(function() {
      this.changeTargetReportPage(1);
    }, 500),
    changeTargetReportPage(page) {
      this.targetReportModal.query.page = page;
      this.getTargetReportList();
    },
    requestReportList(params) {
      return new Promise((resolve, reject) => {
        reportList(params)
          .then((res) => {
            if (res.data.code === 1) {
              let getData = res.data.data;
              let total = getData.totalCount;
              let list = getData.pageData;
              list = list.map((item) => {
                let type = item.type === 1 ? 'attackType' : 'defenseType';
                let currentRule = this.ruleList.find((rule) => rule.id === item[type]);
                item.attackTypeName = item.attackType && currentRule ? currentRule.category : '';
                item.attackLevelName = item.attackLevel;
                item.defenseTypeName = item.defenseType && currentRule ? currentRule.category : '';
                return item;
              });
              resolve({
                list,
                total
              });
            } else {
              this.$Message.warning(res.data.message);
              resolve({
                list: [],
                total: 0
              });
            }
          })
          .catch((err) => {
            console.log(err);
            resolve({
              list: [],
              total: 0
            });
          });
      });
    },
    // 从列表中找出对应ID的名称，无法获取时返回ID
    getValueByList(id, list) {
      let item = list.find((item) => item.id === id);
      return item ? item.name : id;
    },
    // 递归获取级联选择框的数据
    getValueName(value, operatedList, list = []) {
      let item = operatedList.find((item) => item.dictid === value) || {};
      list.unshift(item.dictname);
      if (item.parentid) {
        this.getValueName(item.parentid, operatedList, list);
      }
      return list.join(' / ');
    },
    // 文件列表
    getFileList(data) {
      let { id, type, targetName, groupName } = data;
      this.currentType = type;
      this.fileModal = true;
      this.defeFileList = [];
      reportFileData(id)
        .then((res) => {
          if (res.data.code === 1) {
            this.attackStartTime = res.data.data.startTime;
            this.attackEndTime = res.data.data.endTime;
            this.reportName = res.data.data.reportName;
            this.defeFileList = res.data.data.defenseFiles;
            this.attackFileList = res.data.data.attFiles;
            this.connectRecords = res.data.data.connectRecords;
            this.fileList = res.data.data.files;
            this.currentTargetName = targetName;
            this.groupName = groupName;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    downLoadFile(row) {
      this.currentFileId = row.id;
      this.downloading2 = true;
      let windowsUrl = window.location.origin;
      // windowsUrl = windowsUrl.split('//');
      // let getIp = windowsUrl[1].split('/')[0];
      // getIp = getIp.split(':')[0];
      var objurl = `${windowsUrl}/Learn/${row.path}`;

      // 处理下载地址与当前网站不同源，download属性不生效的问题
      const x = new window.XMLHttpRequest();
      x.open('GET', objurl, true);
      x.responseType = 'blob';
      x.onload = () => {
        this.downloading2 = false;
        const url = window.URL.createObjectURL(x.response);
        const a = document.createElement('a');
        a.href = url;
        a.download = row.name;
        a.click();
      };
      x.onerror = () => {
       // 处理请求失败的情况
        this.downloading2 = false;
        this.$Message.warning('下载失败')
      };
      x.send();
    },
    // 审核
    reviewBtn(row) {
      this.reportID = row.id;
      this.currentTarget = row;
      this.getTopoTargetInfo(row.target)
      let type = row.type === 1 ? 'attackType' : 'defenseType';
      let currentRule = this.ruleList.find((item) => item.id === row[type]) || {};
      console.log(currentRule);
      this.isCheckFirst = true;
      this.formValidate = {
        attackType: currentRule && row.type === 1 ? currentRule.category : '',
        defenseType: currentRule && row.type === 2 ? currentRule.category : '',
        approvalInfo: '',
        status: '',
        attackLevel: row.attackLevel,
        targetType: currentRule.targetType,
        score: currentRule.score || 0,
        // attackLevel: this.getCascaderValue(row.attackLevel, 'attack'),
        type: row.type,
        level: row.level,
        threatType: row.businessLoopholeName,
        loopholeId: row.businessLoopholeId,
        loopholeName: row.businessLoopholeName,
        loopholeCvssv2 : row.businessLoopholeCvssv2,
        loopholeCve : row.businessLoopholeCve,
        loopholeCwe : row.businessLoopholeCwe,
        loopholeTvid : row.businessLoopholeTvid,
        loopholeCnnvd : row.businessLoopholeCnnvd,
        vulnerability : row.businessLoopholeId ? 1 :2,
        vulnerabilities: [{
          threatType:row.businessLoopholeName,
          loopholeCvssv2:row.businessLoopholeCvssv2,
          loopholeCve: row.businessLoopholeCve,
          loopholeCwe:row.businessLoopholeCwe,
          loopholeTvid:row.businessLoopholeTvid,
          loopholeCnnvd:row.businessLoopholeCnnvd,
          step:'',
          sulotion:'',
        }]
      };
      this.changeAttackLevel(this.formValidate.attackLevel);


      // currentTarget.type === 1 ? '攻击' , :防御
      if(this.currentTarget.type !== 1){// 防御的时候 ，选择漏洞 ：只能是
        this.$set(this.formValidate, 'vulnerability', 1);
      }

      this.reviewReportModal = true;
    },
    // 将列表中的危害程度转义为Cascader组件需要的数据格式
    getCascaderValue(val, type) {
      return this.unfoldList(val, type);
    },
    // 多层递归，拼装数据
    unfoldList(val, type, list = []) {
      let templateList = type === 'attack' ? this.attackLevelList : this.defenseTypesList;
      let template = templateList.find((item) => item.dictid === val);
      if (!template) {
        return list;
      }
      list.unshift(val);
      if (template.parentid !== '') {
        // 存在父级元素，递归调用至无父级
        this.unfoldList(template.parentid, type, list);
      }
      return list;
    },
    // 提交审核
    saveReport(name) {
      let attackType = this.currentRule.id;
      this.$refs[name].validate((valid) => {
        if (valid) {
          let params = {
            approvalInfo: this.formValidate.approvalInfo,
            attackType: this.currentTarget.type === 1 ? attackType : '',
            defenseType: this.currentTarget.type === 2 ? attackType : '',
            reportId: this.reportID,
            score: this.formValidate.score,
            status: parseInt(this.formValidate.status),
            attackLevel: this.formValidate.attackLevel
          };
          if (String(params.status) === '2') {
            // 通过时，记录危险等级和攻击方扣分
            params.level = this.formValidate.level;
            params.score = this.formValidate.score;
          }
          if (params.status == '4') {
            params.tag = this.formValidate.tag;
          }
          if([1,2,3].includes(this.hwTypeExtension)){
            params.businessLoopholeCvssv2 = this.formValidate.vulnerabilities.map(item => (item.loopholeCvssv2 || '')).join(',')|| ''
            params.businessLoopholeCwe =  this.formValidate.vulnerabilities.map(item => (item.loopholeCwe || '')).join(',')|| ''
            params.businessLoopholeCve = this.formValidate.vulnerabilities.map(item => (item.loopholeCve || '')).join(',')|| ''
            params.businessLoopholeTvid = this.formValidate.vulnerabilities.map(item => (item.loopholeTvid || '')).join(',')|| ''
            params.businessLoopholeCnnvd = this.formValidate.vulnerabilities.map(item => (item.loopholeCnnvd || '')).join(',')|| ''
            if(this.formValidate.vulnerability == 2){
              params.businessLoopholeName = this.formValidate.vulnerabilities.map(item => (item.threatType || '')).join(',')|| ''
            }else{
              params.businessLoopholeName = this.getLholeName()|| ''
            }
            params.businessLoopholeId = this.formValidate.vulnerability == 1?this.formValidate.loopholeId || '':''
            params.isAddVul = this.formValidate.vulnerability == 1 ? true :false
            params.step =  this.formValidate.vulnerabilities.map(item => (item.step || '')).join(',')
            params.sulotion =  this.formValidate.vulnerabilities.map(item => (item.sulotion || '')).join(',')
          }
          console.log('=======',params);
          // return;
          // if([1,2,3].includes(this.hwTypeExtension)){
          //   params.businessLoopholeCvssv2 = this.formValidate.loopholeCvssv2|| ''
          //   params.businessLoopholeCwe = this.formValidate.loopholeCwe|| ''
          //   params.businessLoopholeCve = this.formValidate.loopholeCve|| ''
          //   params.businessLoopholeTvid = this.formValidate.loopholeTvid|| ''
          //   params.businessLoopholeCnnvd = this.formValidate.loopholeCnnvd|| ''
          //   params.businessLoopholeName = this.getLholeName()|| ''
          //   params.businessLoopholeId = this.formValidate.vulnerability == 1?this.formValidate.loopholeId || '':''
          //   params.isAddVul = this.formValidate.vulnerability == 1 ? true :false
          //   params.step =  this.formValidate.step
          //   params.sulotion =  this.formValidate.sulotion
          // }
          this.submitBtnLoad = true;
          reviewReport(JSON.stringify(params))
            .then((res) => {
              if (res.data.code === 1) {
                this.reviewReportModal = false;
                this.$Message.success({
                  content: '提交成功',
                  duration: 3
                });
                if (this.formValidate.line === '1') {
                  //选择下线并且当前记录未审核
                  lineTarget(this.currentTarget.target).then(({ code, message }) => {});
                }
                this.getReportList();
              } else {
                this.$Message.error({
                  content: res.data.message,
                  duration: 3
                });
              }
              this.submitBtnLoad = false;
            })
            .catch((err) => {
              this.submitBtnLoad = false;
              console.log(err);
            });
        } else {
          this.$Message.error({
            content: '请完善信息！',
            duration: 3
          });
        }
      });
    },

    getLholeName(){ // // 22041 threatType 优先


      if(this.formValidate.vulnerability == 2){
        return this.formValidate.threatType || this.formValidate.loopholeName
      }

      return this.formValidate.loopholeName || this.formValidate.threatType

    },


    cancelModel(name) {
      this.$refs[name].resetFields();
    },
    // 修改审核
    modifyReviewBtn(row) {
      this.reportID = row.id;
      this.getTopoTargetInfo(row.target)
      this.changeAttackLevel(row.attackLevel);
      this.reviewReportModal = true;
      this.currentTarget = row;
      this.isCheckFirst = true;
      let type = row.type === 1 ? 'attackType' : 'defenseType';
      let currentRule = this.ruleList.find((item) => item.id === row[type]) || {};
      this.$set(this.formValidate, 'attackLevel', currentRule.mold);
      this.$set(this.formValidate, 'defenseType', row.type === 2 ? currentRule.category : '');
      this.$set(this.formValidate, 'targetType', currentRule.targetType);
      this.$set(this.formValidate, 'score', row.score || 0);
      this.$set(this.formValidate, 'type', row.type);
      this.$set(this.formValidate, 'tag', row.tag ? row.tag.toString() : '0');
      if([1,2,3].includes(this.hwTypeExtension)){
        let vulnerability = row.businessLoopholeId ? 1 :2
        this.$set(this.formValidate, 'vulnerability', vulnerability);
        this.$set(this.formValidate, 'loopholeId', row.businessLoopholeId);
        this.$set(this.formValidate, 'loopholeName', row.businessLoopholeName);
        this.$set(this.formValidate, 'threatType', row.businessLoopholeName);
        this.$set(this.formValidate, 'loopholeCvssv2', row.businessLoopholeCvssv2);
        this.$set(this.formValidate, 'loopholeCve', row.businessLoopholeCve);
        this.$set(this.formValidate, 'loopholeCwe', row.businessLoopholeCwe);
        this.$set(this.formValidate, 'loopholeTvid', row.businessLoopholeTvid);
        this.$set(this.formValidate, 'loopholeCnnvd', row.businessLoopholeCnnvd);
        this.$set(this.formValidate, 'step', row.step);
        this.$set(this.formValidate, 'sulotion', row.sulotion);
        this.formValidate.vulnerabilities = []
        if(row.businessLoopholeName && row.businessLoopholeName.split(',').length){
          this.setFormData(row)
        }
      }

      // currentTarget.type === 1 ? '攻击' , :防御
      if(this.currentTarget.type !== 1){// 防御的时候 ，选择漏洞 ：只能是
        this.$set(this.formValidate, 'vulnerability', 1);
      }

      this.reviewback = JSON.parse(JSON.stringify(this.formValidate))

      reportFileData(row.id).then((res) => {
          if (res.data.code === 1) {
            let getData = res.data.data;
            this.$set(this.formValidate, 'attackType', row.type === 1 ? currentRule.category : '');
            this.$set(this.formValidate, 'approvalInfo', getData.approvalInfo);
            this.$set(this.formValidate, 'status', String(getData.status));
            this.$set(this.formValidate, 'level', getData.level);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 补充数据
    setFormData(row,flag = false){
      const names = !flag ? row.businessLoopholeName.split(',') : row.threatType.split(',');
      const cvssv2 = !flag ? row.businessLoopholeCvssv2.split(',') : row.loopholeCvssv2.split(',');
      const cve = !flag ? row.businessLoopholeCve.split(',') : row.loopholeCve.split(',');
      const cwe = !flag ? row.businessLoopholeCwe.split(',') : row.loopholeCwe.split(',');
      const tvid = !flag ? row.businessLoopholeTvid.split(',') : row.loopholeTvid.split(',');
      const cnnvd = !flag ? row.businessLoopholeCnnvd.split(',') : row.loopholeCnnvd.split(',');
      const steps = row.step.split(',');
      const sulotions = row.sulotion.split(',');
      const count = names.length;
      for (let i = 0; i < count; i++) {
        this.formValidate.vulnerabilities.push({
          threatType: names[i],
          loopholeCvssv2: cvssv2[i],
          loopholeCve: cve[i],
          loopholeCwe: cwe[i],
          loopholeTvid: tvid[i],
          loopholeCnnvd: cnnvd[i],
          step: steps[i],
          sulotion: sulotions[i]
        })
      }
    },

    // 补充上传文件
    // uploadFile(row){
    //     this.reportID = row.id
    //     this.$refs['uploadIcon'].clearFiles()
    //     this.uploadModal = true
    // },
    // 取消
    cancleUpload() {
      this.$refs['uploadIcon'].clearFiles();
      this.creatFormValidate.file = null;
      this.uploadModal = false;
    },
    handleUploadIcon(file) {
      this.creatFormValidate.file = file;
      return false;
    },
    creatIconHandleSubmit() {
      if (this.creatFormValidate.file == null) {
        this.$Message.error({
          content: '请选择上传文件！',
          duration: 3
        });
        return false;
      }
      this.uploadLoading = true;
      let formData = new window.FormData();
      formData.append('file', this.creatFormValidate.file);
      this.axios
        .post(`${this.baseURL}/referee/referee/upload/${this.reportID}`, formData, {
          headers: { 'Content-type': 'multipart/form-data' },
          timeout:0,
        })
        .then((res) => {
          console.log(res);
          if (res.data.code == 1) {
            this.$Message.success({
              content: '上传成功',
              duration: 3
            });
            this.creatFormValidate.file = null;
            this.uploadModal = false;
            this.getReportList();
          } else {
            this.$Message.error({
              content: res.data.message,
              duration: 3
            });
          }
          this.uploadLoading = false;
        })
        .catch((err) => {
          console.log(err);
          this.uploadLoading = false;
          this.$Message.error('服务器连接失败！');
        });
    },
    // 过滤
    changePageNum(val) {
      this.reportPage = val;
      this.getReportList();
    },
    searchBtn() {
      this.getReportList();
    },
    // 清除
    clearProName() {
      this.serchProjectName = '';
    },
    clearSceneName() {
      this.serchSceneName = '';
    },
    clearTaskName() {
      this.serchTaskName = '';
    },
    changeTime(time, type) {
      if (type === 1) {
        this.searchCheckTime = time;
      } else {
        this.searchUploadTime = time;
      }
      this.reportPage = 1;
      this.getReportList();
    },
    selectStatus() {
      this.reportPage = 1;
      this.getReportList();
    }
  }
};
</script>
<style scoped>
.points-tip {
  margin-top: 4px;
  word-wrap: break-word;
  word-break: break-all;
}
.page-wrap {
  /* padding: 25px; */
}
.page-wrap-query {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-end;
}

.page-wrap-query /deep/ .ivu-cascader-rel .ivu-input {
  border-radius: 20px;
}
.reset-color /deep/ .ivu-select-selected-value {
  color: unset !important;
}
.page-content {
  background-color: #fff;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
}
.img-header {
  display: flex;
  justify-content: space-between;
  /* padding: 20px 20px 0 20px; */
  margin: 15px 0;
  justify-content: flex-end;
}
.addressIcon {
  display: inline-block;
  height: 14px;
  width: 12px;
  background: url('../../assets/globalIcon/addressIcon.png') no-repeat center;
  background-size: 100% 100%;
  margin-bottom: -1px;
}

.flex-between {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.content-wrap {
  overflow-x: hidden;
  overflow-y: auto;
  /* padding: 0 20px; */
  flex: 1;
  height: 0;
}
.content-wrap::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 4px;
}
.content-wrap::-webkit-scrollbar-thumb {
  /*滚动条里面小方块样式*/
  border-radius: 5px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: rgba(209, 209, 209, 0.6);
}
.content-wrap::-webkit-scrollbar-track {
  /*滚动条里面轨道样式*/
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 5px;
  background: rgba(179, 179, 179, 0.1);
}
.noConfirm /deep/ .ivu-picker-confirm button:last-child{
  display: none;
}
.content_border{
  border: 1px dashed var(--divider-color);
  padding: 10px 10px 5px 0px;
  margin-bottom: 8px;
}
.btn_add_style{
  display: flex;
  justify-content:center;
  margin-bottom:5px;
}
</style>
